package cn.gwm.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {
    public static void main(String[] args) {

    }

    /**
     * 使用gzip进行压缩
     *
     * @param str 压缩前的文本
     * @return 返回压缩后的文本
     * @throws IOException 有异常时抛出，由调用者捕获处理
     */
    public static String gzip(String str) throws IOException {
        if (str == null || str.isEmpty()) {
            return str;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (
                GZIPOutputStream gzip = new GZIPOutputStream(out);
        ) {

            gzip.write(str.getBytes());

        }

        return Base64.encodeBase64String(out.toByteArray());
    }

    /**
     * 使用gzip进行解压缩
     *
     * @param compressedStr 压缩字符串
     * @return 解压字符串
     * @throws IOException 有异常时抛出，由调用者捕获处理
     */
    public static String gunzip(String compressedStr) throws IOException {
        if (compressedStr == null || compressedStr.isEmpty()) {
            return compressedStr;
        }

        byte[] compressed = Base64.decodeBase64(compressedStr);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(compressed);

        try (
                GZIPInputStream ginzip = new GZIPInputStream(in);
        ) {

            byte[] buffer = new byte[4096];
            int len = -1;
            while ((len = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
        return out.toString();
    }

}
